import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: qian
 * Date: 2023-01-13
 * Time: 15:18
 */
class MyTask implements Comparable<MyTask>{
    private Runnable runnable;
    private long time;
    public MyTask(Runnable runnable,long delay){
        this.runnable=runnable;
        this.time=System.currentTimeMillis()+delay;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time-o.time);
    }
}
class MyTimer{
    private BlockingQueue<MyTask> queue=new PriorityBlockingQueue<>();
    public static volatile Object locker;
    //创建一个扫描线程
    public MyTimer(){
        Thread t=new Thread(()->{
            while(true){
                try {
                    synchronized (locker) {
                        //取出队首元素
                        MyTask task = queue.take();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {
                            //到点了
                            task.getRunnable().run();
                        } else {
                            //没到点
                            queue.put(task);
                            //等待

                            locker.wait(task.getTime() - curTime);
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });
        t.start();
    }

    public void schedule(Runnable runnable,long after) throws InterruptedException {
        MyTask myTask=new MyTask(runnable,after);
        queue.put(myTask);
        synchronized (locker){
            locker.notify();
        }
    }
}
public class test3 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer myTimer=new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("起床啦");
            }
        },1000);
        System.out.println("开始计时");
    }
}
